import random

from django import http
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
import logging

from celery_tasks.sms.tasks import ccp_send_sms_code
from meiduo_mall.libs.yuntongxun.ccp_sms import CCP

logger = logging.getLogger("django")

from meiduo_mall.libs.captcha.captcha import captcha


class ImageCodeView(View):
    def get(self, request, uuid):
        """

        :param request: 请求对象
        :param uuid: 浏览器端生成的唯一UUID
        :return: 返回验证码图片
        """

        # 调用工具类，caotcha生成图像验证码
        text, image = captcha.generate_captcha()
        captcha.generate_captcha()
        # 连接redis，获取链接对象
        redis_conn = get_redis_connection("verify_code")
        # 保存数据到redis，使用setex函数
        redis_conn.setex("img_%s" % uuid, 300, text)
        return HttpResponse(image,
                            content_type="image/jpg")


class SMSCodeView(View):
    "短信验证码"
    def get(self, request, mobile):
        """

        :param request: 请求对象
        :param mobile: 接收短信的手机号码
        :return: JOSN
        """

        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({
                "code": 400,
                "errmsg": "发送短信过于频繁"
            })
        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({
                "code": 400,
                "errmsg": "缺少必要参数"
            })

        # 创建连接redis的对象
        redis_conn = get_redis_connection("verify_code")
        # 提取图像验证码
        image_code_sever = redis_conn.get("img_%s" % uuid)
        if image_code_sever is None:
            return http.JsonResponse({
                "code": 400, "errmsg": "图形验证码失效"
            })
        # 删除图形验证码
        try:
            redis_conn.delete("img_%s" % uuid)
        except Exception as e:
            logger.error(e)
        # 对比图像验证码
        image_code_sever = image_code_sever.decode()
        if image_code_client.lower() != image_code_sever.lower():
            return http.JsonResponse({
                "code": 400,
                "errmsg": "图像验证码输入有误"
            })
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        # print(sms_code)
        # logger.info((sms_code))
        # # 保存短信验证码
        # redis_conn.setex("sms_%s" % mobile,300,sms_code)
        # # 往 redis 中写入一个数据, 写入什么不重要, 时间重要
        # # 我们给写入的数据设置为60s,如果过期,则会获取不到.
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)

        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, 300, sms_code)
        pl.setex("send_flag_%s" % mobile, 6, 1)
        pl.execute()

        # 发送短信短信验证码
        # CCP().send_template_sms(mobile,[ sms_code, 5], 1)

        # 使用Celery后修改的代码
        # 改为现在的写法, 注意: 这里的函数,调用的时候需要加: .delay()

        """开发阶段取消调用"""
        # ccp_send_sms_code.delay(mobile, sms_code)
        print(sms_code)
        # 返回响应结果
        return http.JsonResponse({
            "code": 0,
            "errmsg": '发送成功'
        })